package com.fy.controller;

import com.fy.common.annotation.GlobalInterceptor;
import com.fy.common.constants.Constants;
import com.fy.pojo.dto.file.DownLoadCodeDTO;
import com.fy.pojo.dto.fileshare.ShareSessionDTO;
import com.fy.pojo.dto.fileshare.ShowShareFileQueryDTO;
import com.fy.pojo.entity.FileInfo;
import com.fy.pojo.vo.file.FoloderVO;
import com.fy.pojo.vo.user.LoginUserVO;
import com.fy.service.ShowShareService;
import com.fy.utils.RedisUtils;
import com.fy.utils.result.PageResult;
import com.fy.utils.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.List;


@Slf4j
@RequestMapping("/showShare")
@RestController
public class ShowShareController extends BaseController {

    @Autowired
    private ShowShareService showShareService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取分享登录信息
     * @param httpSession
     * @param shareId
     * @return
     */
    @PostMapping("/getShareLoginInfo/{shareId}")
    public Result getShareLoginInfo(HttpSession httpSession, @PathVariable String shareId){
        return Result.success(false);
    }

    /**获取分享信息
     *
     * @paam shareId
     * @return
     */
    @PostMapping("/getShareInfo")
    public Result getShareInfo(HttpSession httpSession,String shareId){
        log.info("shareId:{}",shareId);
        Result shareLoginVO=showShareService.getShareInfo(shareId,httpSession);
        log.info("shareLoginVO:{}",shareLoginVO);
        return Result.success(shareLoginVO);
    }

    /**检验分享码
     *
     * @param shareId
     * @param code
     * @return
     */
    @PostMapping("/checkShareCode")
    public Result checkShareCode(HttpSession httpSession,String shareId, String code){

        log.info("shareId:{}",shareId);
        log.info("code:{}",code);
        ShareSessionDTO shareSessionDto=showShareService.checkShareCode(httpSession,shareId,code);

        httpSession.setAttribute(Constants.SESSION_SHARE_KEY + shareId, shareSessionDto);
        return Result.success();
    }

    /**获取分享列表
     *
     * @return
     */
    @PostMapping("/loadFileList")
    public Result loadFileList(HttpSession httpSession,ShowShareFileQueryDTO shareQueryDTO){
        log.info("queryDTO:{}", shareQueryDTO);
        PageResult pageResult=showShareService.loadFileList(httpSession, shareQueryDTO);
        log.info("返回数据封装:{}",pageResult);
        return Result.success(pageResult);
    }


    /**获取发现文件夹目录信息
     *
     * @param shareId
     * @param path
     * @return
     */
    @PostMapping("/getFolderInfo")
    public Result getFolderInfo(String shareId,String path){

        List<FoloderVO> foloderVOList=showShareService.getFolderInfo(path);
        return Result.success(foloderVOList);
    }

    /**查看文件
     *
     * @param shareId
     * @param fileId
     * @return
     */
    @GetMapping("/getFile/{shareId}/{fileId}")
    public void getFile(HttpServletResponse response, @PathVariable String shareId, @PathVariable String fileId){

        FileInfo fileInfo=showShareService.getFilePath(fileId);
        readFile(response, fileInfo.getFilePath());
    }

    /**创建分享文件下载链接
     *
     * @param shareId
     * @param fileId
     * @return
     */
    @PostMapping("/createDownloadUrl/{shareId}/{fileId}")
    @GlobalInterceptor
    public Result createDownloadUrl(@PathVariable String shareId, @PathVariable String fileId) {
        return Result.success(showShareService.createDownloadURL(fileId));
    }

    /**
     * 加载文件夹
     * @param filePid
     * @return
     */
    @PostMapping("/loadMyFolder/{filePid}")
    public Result loadMyFolder(@PathVariable String filePid, HttpSession httpSession){
        return Result.success(showShareService.loadMyFolder(httpSession,filePid));
    }

    /**下载文件
     *
     * @param request
     * @param response
     * @param redisDownLoadKey
     * @throws Exception
     */
    @GetMapping("/download/{code}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String redisDownLoadKey) throws Exception {

        DownLoadCodeDTO dto= (DownLoadCodeDTO) redisUtils.get(redisDownLoadKey);
        log.info("redis中的下载数据:{}",dto);
        if (null == dto) {
            return;
        }
        String filePath = dto.getFilePath();
        String fileName = dto.getFileName();
        response.setContentType("application/x-msdownload; charset=UTF-8");
        if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {//IE浏览器
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        readFile(response, filePath);
    }

    /**保存分享文件
     *
     * @param httpSession
     * @param shareId
     * @param shareFileIds
     * @param myFolderId
     * @return
     */
    @PostMapping("/saveShare")
    @GlobalInterceptor
    public Result saveShare(HttpSession httpSession,String shareId,String shareFileIds, String myFolderId){
        LoginUserVO loginUserVO=(LoginUserVO) httpSession.getAttribute(Constants.SESSION_KEY);
        showShareService.saveShare(loginUserVO,shareId,shareFileIds,myFolderId);
        return Result.success();
    }
}
